package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.ShipmentCompareDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.ShelfOnLocation;
import com.mflex.mwms.model.ShipmentCompareRequest;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ShipmentCompareDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

//    @BindView(R.id.stv_ShipmentId)
//    EditText stvShipmentId;

    @BindView(R.id.stv_BoxQty)
    EditText stvBoxQty;

    @BindView(R.id.stv_Qty)
    EditText stvQty;

    @BindView(R.id.stv_TaskNoLabel)
    EditText stvTaskNoLabel;

    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_submit)
    Button buttonSubmit;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;


    MiniLoadingDialog mMiniLoadingDialog;

    private int scanQty = 0;
    private int scanBoxQty = 0;

    private Task task;

    private List<TaskDetail> taskDetailList;

    private Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shipment_compare_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        stvBoxNumber.setOnKeyListener(this);
        stvTaskNoLabel.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);
//        requestTask(this.getCurrentFocus());
        stvTaskNoLabel.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvTaskNoLabel.requestFocus();
            }
        }, 200);


        Intent intent = getIntent();
        Type listType = new TypeToken<Task>() {
        }.getType();
        task = (Task) JsonUtil.fromJson(intent.getStringExtra("task"), listType);

        taskDetailList = task.getTaskDetails();

        ShipmentCompareDetailAdapter shipmentCompareDetailAdapter = new ShipmentCompareDetailAdapter(ShipmentCompareDetailActivity.this, taskDetailList);
        lvTaskList.setAdapter(shipmentCompareDetailAdapter);

        stvTaskNo.setText(task.getTaskNo());
        stvBoxQty.setText(String.valueOf(scanBoxQty) + "/" + String.valueOf(task.getTaskDetails().size()));
        stvQty.setText(String.valueOf(scanQty) + "/" + String.valueOf(task.getStockoutDetails().get(0).getQty()));

        Log.d("task", "onStart GetCompareSession");
        timer.schedule(new MyTimerTask(), 0, 1000 * 60 * 5);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_submit:
                SubmitButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_TaskNo:
//                    checkWarehouse(view);
                    break;
                case R.id.stv_BoxNumber:
//                    requestTask(view);
                    checkBox(view);
                    break;
                case R.id.stv_TaskNoLabel:
                    checkTaskNoLabel(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void checkBox(View view) {
        if (StringUtils.isEmpty(stvTaskNoLabel.getText().toString())) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("标签任务号未输入")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "标签任务号未输入");
            stvBoxNumber.setText("");
            stvTaskNoLabel.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvTaskNoLabel.requestFocus();
                }
            }, 200);
            return;
        }

        boolean flag = false;
        boolean isexist = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                isexist = true;
                break;
            }
        }
        if (!isexist) {
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱不在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "箱不在列表中");
            return;
        }
        int qtyn = 0;
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName()) && taskDetail.isChecked()) {
                flag = true;
            }
        }
        if (flag) {
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "箱已在列表中");
            return;
        }
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                qtyn = Integer.parseInt(taskDetail.getQty());
                taskDetail.setChecked(true);
            }
        }
        Collections.sort(taskDetailList, new Comparator<TaskDetail>() {
            @Override
            public int compare(TaskDetail t0, TaskDetail t1) {
                if (!t0.isChecked() && t1.isChecked()) {
                    return -1;
                }
                return 0;
            }
        });

        ShipmentCompareDetailAdapter shipmentCompareDetailAdapter = new ShipmentCompareDetailAdapter(ShipmentCompareDetailActivity.this, taskDetailList);
        lvTaskList.setAdapter(shipmentCompareDetailAdapter);
        stvBoxNumber.setText("");
        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);

        scanQty = scanQty + qtyn;
        scanBoxQty = scanBoxQty + 1;
        stvBoxQty.setText(String.valueOf(scanBoxQty) + "/" + String.valueOf(taskDetailList.size()));
        stvQty.setText(String.valueOf(scanQty) + "/" + String.valueOf(task.getStockoutDetails().get(0).getQty()));

        stvBoxNumber.setText("");
        stvTaskNoLabel.setText("");
        stvTaskNoLabel.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvTaskNoLabel.requestFocus();
            }
        }, 200);
    }

    private void clearButtonMd(View v) {
        scanQty = 0;
        scanBoxQty = 0;
        stvBoxNumber.setText("");
        stvTaskNo.setText("");
        stvQty.setText("");
        stvBoxQty.setText("");
        taskDetailList = new ArrayList<>();
        ShipmentCompareDetailAdapter shipmentCompareDetailAdapter = new ShipmentCompareDetailAdapter(ShipmentCompareDetailActivity.this, taskDetailList);
        lvTaskList.setAdapter(shipmentCompareDetailAdapter);
        XToastUtils.success("重置成功！");
    }

    private void SubmitButtonMd(View view) {

        if (CollectionUtils.isEmpty(taskDetailList)) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("提交列表为空")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "提交列表为空");
            return;
        }


        boolean flag = true;
        for (TaskDetail taskDetail : taskDetailList) {
            if (!taskDetail.isChecked()) {
                flag = false;
                break;
            }
        }
        if (!flag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("没有全部比对")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "没有全部比对");
            return;
        }

        ShipmentCompareRequest shipmentCompareRequest = new ShipmentCompareRequest();
        shipmentCompareRequest.setTaskNo(stvTaskNo.getText().toString());
        shipmentCompareRequest.setWarehouse(MMKVUtils.getString("Warehose", ""));
        mMiniLoadingDialog.show();
        XHttp.post("api/Comparison/ShipmentCompare")
                .upJson(JsonUtil.toJson(shipmentCompareRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("比对成功", 2500);

//                        stvBoxNumber.setText("");
//                        stvTaskNo.setText("");
//                        stvShipmentId.setText("");
//                        scanQty = 0;
//                        totalQty = 0;
//                        stvBoxQty.setText("");
//                        taskDetailList = new ArrayList<>();
//                        ShipmentCompareDetailAdapter shipmentCompareDetailAdapter = new ShipmentCompareDetailAdapter(ShipmentCompareDetailActivity.this, taskDetailList);
//                        lvTaskList.setAdapter(shipmentCompareDetailAdapter);
//
//                        stvTaskNo.requestFocus();
                        setResult(0);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(view.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, e);
                    }
                }) {
                });
    }

    private void checkTaskNoLabel(View view) {
        if (StringUtils.isEmpty(stvTaskNoLabel.getText().toString())) {
            return;
        }
        if (!StringUtils.equals(stvTaskNoLabel.getText().toString(), task.getTaskNo())) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("标签任务号与任务不匹配")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, "标签任务号与任务不匹配");
            stvTaskNoLabel.setText("");
            stvTaskNoLabel.requestFocus();
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d("task", "cancel GetCompareSession");
        timer.cancel();
    }

//    @Override
//    public void onStart() {
//        super.onStart();
//        Log.d("task", "onStart GetCompareSession");
//        timer.schedule(new MyTimerTask(), 0, 1000 * 10);
//    }
//
//    @Override
//    public void onStop() {
//        super.onStop();
//        Log.d("task", "cancel GetCompareSession");
//        timer.cancel();
//    }

    public class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            Log.d("task", "start GetCompareSession");
            XHttp.get("api/Comparison/GetCompareSession")
                    .syncRequest(false)
                    .onMainThread(true)
                    .accessToken(true)
                    .timeOut(120000)
                    .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                        @Override
                        public void onSuccess(String response) {

                        }

                        @Override
                        public void onError(ApiException e) {
                            mMiniLoadingDialog.dismiss();
                            MessageUtils.errorMsgAndVoice(ShipmentCompareDetailActivity.this, e);
                        }
                    }) {
                    });
        }
    }
}